/*
 * PhysicWorld.cpp
 * This file is part of FunBall 
 *
 * Copyright (C) 2012 - Francois Berder
 *
 * FunBall is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * FunBall is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
 
 

#include "PhysicWorld.hpp"
#include "MyContactListener.hpp"
#include <cassert>

inline PhysicObject& CREATE_PHYSIC_OBJECT(const json::Object& data)
{
    return PhysicWorld::instance().createObject(data);
}


PhysicWorld::PhysicWorld():
m_world(NULL)
{
}

PhysicWorld::PhysicWorld(const PhysicWorld& pw):
m_world(pw.m_world)
{
}
PhysicWorld::~PhysicWorld()
{
    destroyWorld();
}   

PhysicWorld& PhysicWorld::operator=(const PhysicWorld& pw)
{
    m_world = pw.m_world;
    return *this;
}
PhysicWorld& PhysicWorld::instance()
{
    static PhysicWorld pw;
    return pw;
}

void PhysicWorld::createWorld()
{
    destroyWorld();
    m_world = new b2World(b2Vec2(0,-10.f),true);
    m_world->SetContactListener(new MyContactListener());
}

void PhysicWorld::destroyWorld()
{
    if(m_world)
        delete m_world;
    
    m_world = NULL;
}

b2World* PhysicWorld::world()
{
    assert(m_world != NULL);
    
    return m_world;
}

void PhysicWorld::update(const float dt)
{
    assert(m_world != NULL);
    
    m_world->Step(dt,10,5);
    m_world->ClearForces();
}

PhysicObject& PhysicWorld::createObject(const json::Object& data)
{
    PhysicObject o;
    o.load(data);
    return o;
}
